package com.leetcode.算法策略相关.动态规划;

import java.util.Arrays;

/**
 * @author: xiaomi
 * @date: 2021/2/5
 * @description: 518. 零钱兑换 II
 * https://leetcode-cn.com/problems/coin-change-2/
 * 类似 {@link B_322_零钱兑换}
 */
public class B_518_零钱兑换_II {

    public static void main(String[] args) {
        B_518_零钱兑换_II action = new B_518_零钱兑换_II();
        test1(action);

    }

    public static void test1(B_518_零钱兑换_II action) {
        //4
        int[] coins = new int[]{1, 2, 5};
        int amount = 5;
        int res = action.change(amount, coins);
        System.out.println("res = " + res);
    }

    /**
     * 使用动态规划
     * dp[i] = dp[i-coins[i1]] + dp[i-coins[i2]] + ... + dp[i-coins[ix]]
     *
     * @param amount
     * @param coins
     * @return
     */
    public int change(int amount, int[] coins) {
        int len = coins.length;
        Arrays.sort(coins);
        if (amount < coins[0]) {
            return 0;
        }
        int[] dp = new int[amount + 1];
        for (int i = 0; i < coins[0]; i++) {
            dp[i] = 0;
        }
        //1.初始化硬币处-> 设置为 1
        for (int i = 0; i < len; i++) {
            if (coins[i] <= amount) {
                dp[coins[i]] = 1;
            }
        }
        for (int i = coins[0] + 1; i <= amount; i++) {
            for (int j = 0; j < len; j++) {
                int value = i - coins[j];
                if (value <= 0) {
                    break;
                }
                dp[i] += dp[value];
            }
        }
        return dp[amount];
    }
}
